package cn.itcast.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/*
* @PackageName:cn.itcast.controller
* @Class:UserController
* @author:ledehui
* @Date:2020/11/2 10:31
*/
@Controller
@RequestMapping("/user1")
public class UserController1 {

    @RequestMapping("/fileupload1")
    public String testFileuoload1(HttpServletRequest request ) throws  Exception {
        System.out.println("testFileuoload1.....");
//        使用fileupload组件完成文件上传
//        上传的位置
        String  path = request.getSession().getServletContext().getRealPath("/uploads/");
//        判断，该路径是否存在
        File file = new File(path);
        if (!file.exists()){
            System.out.println("testFileuoload1.....1");
            //创建该文件夹
            file.mkdirs();

        }
        //解析request对象，回去上传文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //开始解析request
        List<FileItem> items = upload.parseRequest(request);
        System.out.println(items);
        //遍历
        for(FileItem item:items){
            System.out.println("testFileuoload1.....5");
            //进行判断，当前item对象是否是上传文件项
            if (item.isFormField()){

                System.out.println("testFileuoload1.....3");
                //说明普通表单项
            }else {
                System.out.println("testFileuoload1.....4");
                //说明上传文件项
//                获取到上传文件的名称
                String filename = item.getName();
                //完成文件上传
                item.write(new File(path,filename));
                //删除临时文件
                item.delete();
                System.out.println("testFileuoload1.....");
            }
        }

        return "success";
    }
}
